#include "be_atomic.h"
#include "cd_obj_pool.h"

CD_NAMESPACE_BEGIN

volatile	s32	c_obj_pool::lck	=	0;
c_smp_obj_pool	c_obj_pool::pool;


static	s32	lock(volatile	s32*	lk)
{
	while (be::atomic_compare_exchange32(
		lk,	1,	0)	!=	0);
	return	en_sucess;
}

static	s32	unlock(volatile	s32*	lk)
{
	while (be::atomic_compare_exchange32(
		lk,	0,	1)	!=	0);
	return	en_sucess;
}

c_smp_obj_pool::~c_smp_obj_pool()
{

}
c_object*	c_smp_obj_pool::allocate(c_entity*	ent,
		s32	lcktype)
{
	c_object*	obj	=	NULL;
	node*		nod	=	head;
	if(head){
		obj		=	(c_object*)head;
		head	=	head->next;
		obj->m_entity	=	ent;
		obj->m_lcktype		=	lcktype;
	}

	return	obj;
}

void		c_smp_obj_pool::deallocate(c_object*	obj)
{
	if(!obj){
		return;
	}
	obj->clear(NULL);
	node*		nod	=	(node*)obj;
	nod->next	=	head;
	head	=	nod;
}

c_object*	c_obj_pool::allocate(c_entity*	ent,s32	type)
{
	c_object*	obj	=	0;
	lock(&lck);
	obj	=	pool.allocate(ent);
	unlock(&lck);
	if(!obj){
		obj	=	new	c_object(ent,	type);
	}
	return	obj;
}
void		c_obj_pool::deallocate(c_object*	obj)
{
	if(!obj)	return;
	lock(&lck);
	pool.deallocate(obj);
	unlock(&lck);
}

CD_NAMESPACE_END
